package SERVER;



//import Player;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * Obsluga jednego polaczenia z klientem
 * @author Miroslaw
 *
 */
public class PlayerServerThread extends Thread
{
	Socket client = null;
	BufferedReader in = null;
	PrintWriter out = null;
	String line = " ";
	Hand hand;
	int chips = 0;
	boolean dealer_button, big_blind, small_blind;
	//static Player player = new Player();
	int player_id=0;
	String nickname;
	
	
	PlayerServerThread(Socket socket)
	{
		this.client = socket;
		hand = new Hand();
	}
	
	public synchronized void run()
	{
		System.out.println("Created a connection with "+ client.getRemoteSocketAddress()+" "+player_id);
		GlobalVar.players_connected++;
		try 
		{
			in = new BufferedReader(new InputStreamReader(client.getInputStream()));
			out = new PrintWriter(client.getOutputStream(), true);
		} 
		catch (IOException e) 
		{
			System.out.println("I/O Error"); //System.exit(-1);
		}

		ServerStart.game_server.CheckTheGame();

		
		while(line!=null)
		{
			try
			{
				line = in.readLine();
				String [] message = line.split(" ");
				if(message[0].equals("Quit"))
				{
					break;
				}
				else if (message[0].equals("Nick"))
				{
					nickname = message[1];
					System.out.println(nickname);
				}
			}
			catch(IOException IOE)
			{
				System.out.println("Input/Output operation error");
				break;
			}
		}
		
		try
		{
			in.close();
			out.close();
			client.close();
			System.out.println("Stopped connection with " + client.getRemoteSocketAddress() + "   " + player_id);
			GlobalVar.players_connected--;
			int index = ServerStart.player.indexOf(this);
			ServerStart.player.remove(this);
			ServerStart.game_server.delete_player_info(index);
			System.out.println("Size " + ServerStart.player.size());

		}
		catch(IOException IOE)
		{
			System.out.println("Can't ending the connection");
			System.exit(-1);
		}
	}

	public void setCardInHand(int card, int card_id)
	{
		hand.setCard(card, card_id);
	}

	public Card getCardFromHand(int card)
	{
		return hand.getCard(card);
	}

	public void setChips(int chips)
	{
		this.chips = chips;
	}

	public int getChips()
	{
		return this.chips;
	}

	public void changeChips(int chips_changed, char operation)
	{
		if(operation=='+')
		{
			this.chips=this.chips+chips_changed;
		}
		else if(operation=='-')
		{
			this.chips=this.chips-chips_changed;
		}
	}
	public void setDealerButton(boolean status)
	{
		this.dealer_button=status;
	}
	public void setBigBlind(boolean status)
	{
		this.big_blind=status;
	}
	public void setSmallBlind(boolean status)
	{
		this.small_blind=status;
	}

}
